import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// 题目:
/// 竖屏平均放几个, 横屏状态也要放几个
/// 比如: 竖屏能放5个,横屏也要能放5个
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('build');
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Material App Bar'),
        ),
        body: Body3(),
      ),
    );
  }
}

/// 思路一: 通过 MediaQuery 屏幕方向适配
class Body1 extends StatelessWidget {
  const Body1({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Flex(
        // MediaQuery 可以获取屏幕信息,比如宽高,横竖屏等
        direction: MediaQuery.of(context).orientation == Orientation.portrait
            ? Axis.vertical
            : Axis.horizontal,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: List.generate(
            5,
            (index) => Container(
                  width: 100,
                  height: 100,
                  color: Colors.primaries[index],
                )),
      ),
    );
  }
}

/// 思路二: 通过LayoutBuilder判断屏幕方向适配
class Body2 extends StatelessWidget {
  const Body2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return Center(
          child: Flex(
            // constraints 获得的是可以绘制的区域
            direction: constraints.maxHeight > constraints.maxWidth
                ? Axis.vertical
                : Axis.horizontal,
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: List.generate(
                5,
                (index) => Container(
                      width: 100,
                      height: 100,
                      color: Colors.primaries[index],
                    )),
          ),
        );
      },
    );
  }
}

/// 思路三: 通过LayoutBuilder判断屏幕方向适配
class Body3 extends StatelessWidget {
  const Body3({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return OrientationBuilder(builder: (ctx, orientation) {
      return Center(
          child: Flex(
            // constraints 获得的是可以绘制的区域
            direction: orientation == Orientation.portrait
                ? Axis.vertical
                : Axis.horizontal,
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: List.generate(
                5,
                (index) => Container(
                      width: 100,
                      height: 100,
                      color: Colors.primaries[index],
                    )),
          ),
        );
    });
  }
}